import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Roles } from './roles.decorator';

const matchRoles = (roles: string[], userRoles: string[]) => {
  console.log(roles, userRoles, '=====');
  return roles.some((role) => userRoles?.includes(role));
};

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private reflector: Reflector) {}

  canActivate(context: ExecutionContext): boolean {
    const roles = this.reflector.get(Roles, context.getHandler());
    if (!roles) {
      return false;
    }
    const request = context.switchToHttp().getRequest();
    const user = request.user;
    console.log(user, '=====user');
    console.log(roles, user?.roles, '=====');
    return matchRoles(roles, user?.roles);
  }
}
